package cn.hinglo.gameclaw.data.interceptors;

import cn.hinglo.gameclaw.data.entity.Result;
import cn.hinglo.gameclaw.data.enums.ExceptionEnum;
import cn.hinglo.gameclaw.data.utils.JwtUtil;
import cn.hinglo.gameclaw.data.utils.ResultUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.java.Log;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static cn.hinglo.gameclaw.data.utils.FieldUtils.AUTHORIZATION;


/**
 * @createTime: 2018/1/4
 * @author: HingLo
 * @description: 访问登录拦截器
 */
@Log
public class LoginInterceptors extends BaseInterceptor {

    private final String prefix = "ClawGame";
    /**
     * token 的指定header
     */
    private final String authorization = AUTHORIZATION;
    String userId = "";
    String subject = "";


    @Override
    boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler, HandlerMethod handlerMethod) throws Exception {
        String authHeader = request.getHeader(authorization);
        if (authHeader == null || !authHeader.startsWith(prefix)) {
            Result result = ResultUtils.error(ExceptionEnum.HEADERERROR);
            ResultUtils.error(response, result);
            return false;
        } else {
            // 取得token
            try {
                String token = authHeader.substring(prefix.length());
                //检测token是否有效
                Claims claims = JwtUtil.parseJWT(token);
                //获取登录信息的id
                userId = claims.getId();
                //登录用户的信息Json格式字符串
                subject = claims.getSubject();
                //其他详细认证处理   需要使用subject 与 UserId
            } catch (Exception e) {
                //token 失效
                Result result = ResultUtils.error(ExceptionEnum.TOKENINVALID);
                ResultUtils.error(response, result);
                return false;
            }
        }
        response.setHeader(AUTHORIZATION, JwtUtil.createJWT(userId, subject));
        return true;
    }


}
